package com.jzo2o.health.handler;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.jzo2o.api.orders.dto.request.OrderCancelReqDTO;
import com.jzo2o.api.trade.RefundRecordApi;
import com.jzo2o.api.trade.dto.response.ExecutionResultResDTO;
import com.jzo2o.common.constants.UserType;
import com.jzo2o.health.enums.OrderPayStatusEnum;
import com.jzo2o.health.enums.OrderStatusEnum;
import com.jzo2o.health.mapper.OrdersMapper;
import com.jzo2o.health.mapper.OrdersRefundMapper;
import com.jzo2o.health.model.domain.Orders;
import com.jzo2o.health.model.domain.OrdersRefund;
import com.jzo2o.health.model.dto.request.OrdersCancelReqDTO;
import com.jzo2o.health.properties.OrdersJobProperties;
import com.jzo2o.health.service.IOrdersService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 订单相关定时任务
 *
 * @author itcast
 * @create 2023/9/2 16:44
 **/
@Slf4j
@Component
public class OrdersHandler {

    @Resource
    private RefundRecordApi refundRecordApi;
    //解决同级方法调用，事务失效问题
    @Resource
    private OrdersHandler orderHandler;
    @Resource
    private OrdersJobProperties ordersJobProperties;
    @Autowired
    private OrdersRefundMapper ordersRefundMapper;

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private IOrdersService ordersService;
    /**
     * 支付超时取消订单
     * 每分钟执行一次
     */
    @XxlJob(value = "cancelOverTimePayOrder")
    public void cancelOverTimePayOrder() {
        //1、根据订单创建时间查询超过15分钟未支付的订单
        List<Orders> orders = ordersService.lambdaQuery()
                .eq(Orders::getPayStatus, OrderStatusEnum.NO_PAY.getStatus())//查询待支付状态的订单
                .lt(Orders::getCreateTime, LocalDateTime.now().minusMinutes(15))//小于当前时间减去15分钟
                .last("limit " + 100)
                .list();
        if (CollUtil.isEmpty(orders)) {
            return;
        }

        //2、循环修改所有订单状态
        orders.forEach(o -> {
            OrdersCancelReqDTO ordersCancelReqDTO = new OrdersCancelReqDTO();
            ordersCancelReqDTO.setCancelReason("超时未支付，自动取消！");
            ordersCancelReqDTO.setId(o.getId());
            ordersService.cancel(ordersCancelReqDTO);
        });
    }

    /**
     * 订单退款异步任务
     */
    @XxlJob(value = "handleRefundOrders")
    public void handleRefundOrders() {
        //查询退款中订单
        List<OrdersRefund> ordersRefundList = ordersRefundMapper.selectList(null);
        for (OrdersRefund ordersRefund : ordersRefundList) {
            //调用第三方退款
            ExecutionResultResDTO executionResultResDTO
                    = refundRecordApi.refundTrading(ordersRefund.getTradingOrderNo(), ordersRefund.getRealPayAmount());
            //处理退款后内容
            if (executionResultResDTO != null) {
                //1. 从响应结果中确定退款状态
                if (executionResultResDTO.getRefundStatus() <= 1) {
                    return;//0:发起退款 1：退款中
                }

                //2. 更新订单表中的退款状态
                Orders orders = new Orders();
                orders.setPayStatus(executionResultResDTO.getRefundStatus() + 1);
                orders.setId(ordersRefund.getId());
                int result = ordersMapper.updateById(orders);

                //3. 删除待退款表中记录
                if (result > 0) {
                    ordersRefundMapper.deleteById(ordersRefund.getId());
                }
            }
        }
    }

}
